<?php

namespace app\controllers\h5\my;

use app\controllers\h5\base\H5Controller;
use app\models\user\User;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class TeamController extends H5Controller
{
    public function actionList()
    {
        $type = intval($this->post('type'));
        $ids = [-1];

        if ($type == 0) {
            // all
            $list = Chain::getChildrenAll($this->user->id);
            $ids = ArrayHelper::getColumn($list, 'id');
        } else if ($type == 1) {
            // first
            $list = Chain::getChildren($this->user->id);
            $ids = ArrayHelper::getColumn($list, 'id');
        } else if ($type == 2) {
            // not first
            $all = Chain::getChildrenAll($this->user->id);
            $first = Chain::getChildren($this->user->id);
            $all_ids = ArrayHelper::getColumn($all, 'id');
            $first_ids = ArrayHelper::getColumn($first, 'id');
            $ids = array_diff($all_ids, $first_ids);
        }

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = User::find()
            ->where(['status' => User::$statusMapping['OK']])
            ->andWhere(['id' => $ids]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['level0'])
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            unset($item['password']);
            $item['nickname'] = base64_decode($item['nickname']);
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }
}